<template>
  <div>
    <!--  分隔   -->
    <el-row>
      <el-col :span="24"><div class="grid-content bg-purple-light">
        <div style="float: left; margin: 20px 100px; font-weight: 700;color:#606266;font-size: 20px"><i class="el-icon-search"></i>用户查询</div>
      </div></el-col>
    </el-row>
    <!--  查询条件-->
    <el-form :inline="true" :model="queryForm" style="text-align: left; margin: 0 10%">
      <el-form-item label="账号">
        <el-input v-model="queryForm.userId" placeholder="账号" clearable></el-input>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="queryForm.userName" placeholder="姓名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="getList" plain>查询</el-button>
        <el-button type="info" @click="add()" plain>新增</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24"><div class="grid-content bg-purple-light">
        <div style="float: left; margin: 0 100px; font-weight: 700;color:#606266;font-size: 20px"><i class="el-icon-s-unfold"></i>数据列表</div>
      </div></el-col>
    </el-row>
    <div id="s" class="animate__animated animate__zoomIn animate__delay-1s" style="margin-top: 20px">
    <!--  数据表格-->
    <el-table :data="tableData" stripe style="width: 100%;" :border="true"
              :header-cell-style="{background:'#209e91', color:'#ffffff',textAlign:'center'}">
      <el-table-column
        prop="userId"
        label="账号"
        align="center">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="姓名"
        align="center">
      </el-table-column>
      <el-table-column
        prop="sex"
        label="性别"
        align="center">
      </el-table-column>
      <el-table-column
        prop="telephone"
        label="电话"
        align="center">
      </el-table-column>
      <el-table-column
        prop=""
        label="拥有角色"
        align="center">
        <template v-slot="scope">
          <el-tag v-for="item in scope.row.sysRoleList" :type="item.name=='管理员'?'warning':''" :key="item.id" style="margin: 5px;color: #209e91" >{{ item.name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createId"
        label="新增人员"
        align="center">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="新增时间"
        width="180px"
        align="center">
      </el-table-column>
      <el-table-column
        prop="modifyId"
        label="修改人员"
        align="center">
      </el-table-column>
      <el-table-column
        prop="modifyTime"
        label="修改时间"
        width="180px"
        align="center">
      </el-table-column>
      <el-table-column
        label="操作"
        width="150"
        align="center">
        <template v-slot="scope">
          <el-button @click="edit(scope.row)" type="text" size="small" >编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="remove(scope.row)">
            <el-button slot="reference" type="text" size="small">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
      <el-row>
        <el-col :span="24"><div class="grid-content bg-purple-light">
          <div style="margin: 20px"></div>
        </div></el-col>
      </el-row>
    <!--  分页-->
    <el-pagination
      @size-change="getList"
      @current-change="getList"
      :current-page.sync="queryForm.pageNum"
      :page-sizes="[10, 20, 30, 40, 60, 80, 100]"
      :page-size.sync="queryForm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
      <el-row>
        <el-col :span="24"><div class="grid-content bg-purple-light">
          <div style="margin: 20px"></div>
        </div></el-col>
      </el-row>
    </div>
    <!--  新增/修改页面-->
    <el-dialog
      :title="title"
      :visible.sync="show"
      width="30%">
      <span>
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px">
          <el-form-item label="账号" prop="userId">
             <el-input v-model="form.userId" :disabled="disabled"></el-input>
          </el-form-item>
           <el-form-item label="姓名" prop="userName">
             <el-input v-model="form.userName"></el-input>
          </el-form-item>
           <el-form-item label="密码" prop="password">
             <el-input v-model="form.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="重复" prop="checkPassword">
             <el-input v-model="form.checkPassword" show-password></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
             <el-select v-model="form.sex" placeholder="请选择">
<!--                :label="item.label"-->
                <el-option
                  v-for="item in sexList"
                  :key="item.value"
                  :value="item.value">
                </el-option>
             </el-select>
          </el-form-item>
          <el-form-item label="电话" prop="telephone">
             <el-input v-model="form.telephone" ></el-input>
          </el-form-item>
           <el-form-item label="角色">
              <el-select v-model="form.sysRoleList" value-key="name" multiple placeholder="请选择">
                <el-option
                  v-for="item in sysRoleListOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
                </el-option>
              </el-select>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "SysUser",
  data() {
    let checkPassword = (rule, value, callback) => {
      if ((value === '' || undefined === value) && this.form.password != '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password && this.form.password != '') {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      //查询对象
      queryForm: {
        userId: '',
        userName: '',
        pageNum: 1,
        pageSize: 10
      },
      //表格数组
      tableData: [],
      //共多少条
      total: 0,
      //表单对象
      form: {
        sysRoleList: []
      },
      //显示新增、修改
      show: false,
      //标题
      title: '',
      disabled: false,
      sexList: [
        {
          value: '男',
        },
        {
          value: '女',
        }
      ],
      sysRoleListOptions: [],
      //校验对象
      rules: {
        userId: [
          {required: true, message: '请输入用户账号', trigger: 'blur'},
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        userName: [{required: true, message: '请输入用户名称', trigger: 'blur'}],
        sex: [{required: true, message: '请选择性别', trigger: 'change'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        telephone:[
          {required: true, message: '请输入电话', trigger: 'blur'},
          {min: 11, max: 11, message: '请输入正确格式的电话号码', trigger: 'blur'}
        ],
        checkPassword: [{required: true, validator: checkPassword, trigger: 'blur'}]
      }
    }
  },
  methods: {
    getList() {
      this.$axios({
        url: 'sys/user/list',
        method: 'post',
        data: this.queryForm
      }).then(res => {
        if (res.data.success) {
          this.tableData = res.data.object.list;
          this.total = res.data.object.total;
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    getRoleList() {
      this.$axios({
        url: 'sys/role/listAll',
        method: 'post'
      }).then(res => {
        if (res.data.success) {
          this.sysRoleListOptions = res.data.object;
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    success() {
      this.getList()
    },
    add() {
      //设置标题
      this.title = '新增'
      //显示对话框
      this.show = true
      //清空表单
      this.form = {}
      //清空校验结果
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate();
      })
      this.disabled = false
      this.rules.password[0].required = true;
      this.rules.checkPassword[0].required = true;
    },
    edit(row) {
      this.title = '修改'
      //清空表单
      this.form = {}
      //给form对象赋值
      this.form = Object.assign({}, row);
      //清空密码
      this.form.password = ''
      //设置角色下拉菜单
      this.form.sysRoleIds = [];
      if(row.sysRoleList!=undefined){
        for(let i = 0 ; i < row.sysRoleList.length; i++){
          let role = row.sysRoleList[i];
          this.form.sysRoleIds.push(role.id)
        }
      }
      //显示对话框
      this.show = true
      //清空校验结果
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate();
      })
      this.disabled = true
      this.rules.password[0].required = false;
      this.rules.checkPassword[0].required = false;
    },
    remove(row) {
      this.$axios({
        url: 'sys/user/remove/' + row.id,
        method: 'post'
      }).then(res => {
        if (res.data.success) {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
          this.getList();
        } else {
          this.$message.error(res.data.message);
        }
      }).catch(err => {
        this.$message.error(err.message);
      })
    },
    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          //校验通过
          if (this.title == '新增') {
            this.$refs['ruleForm'].validate((valid) => {
              if (valid) {
                this.$axios({
                  url: 'sys/user/add',
                  method: 'post',
                  data: this.form
                }).then(res => {
                  if (res.data.success) {
                    this.show = false;
                    this.getList()
                  } else {
                    this.$message.error(res.data.message);
                  }
                }).catch(err => {
                  this.$message.error(err.message);
                })
              }
            });
          } else {
            this.$axios({
              url: 'sys/user/edit',
              method: 'post',
              data: this.form
            }).then(res => {
              if (res.data.success) {
                this.show = false;
                this.getList()
              } else {
                this.$message.error(res.data.message);
              }
            }).catch(err => {
              this.$message.error(err.message);
            })
          }
        }
      });
    },
    // change(row) {
    //   this.$confirm('确认更改用户状态?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     this.$axios({
    //       url: 'sys/user/change',
    //       method: 'post',
    //       data: row
    //     }).then(res => {
    //       if (res.data.success) {
    //         this.$message({
    //           message: res.data.message,
    //           type: 'success'
    //         });
    //       } else {
    //         this.$message.error(res.data.message);
    //       }
    //     }).catch(err => {
    //       row.status = row.status == '1' ? '0' : '1';
    //       this.$message.error(err.message);
    //     })
    //   }).catch(() => {
    //     row.status = row.status == '1' ? '0' : '1';
    //     this.$message({
    //       type: 'info',
    //       message: '已取消操作'
    //     });
    //   });
    // }
  },
  created() {
    this.getList()
    this.getRoleList()
  }
}
</script>

<style scoped>
.el-select {
  width: 100%;
}
.el-button--info:hover {
  background: #209e91;
  border-color: #209e91;
  color: #FFF;
}
#s{
  width:90%;
  margin:10px auto;
  background-color: #ffffff;
  box-shadow: 10px 10px 5px #c4c6c7;
  border-radius: 5px
}
</style>
